/*
 * @(#)EditMessageDetailAction.java 
 * Copyright (c) 2006 DCIVision Ltd All rights reserved. This software is the confidential and proprietary information of DCIVision Ltd ("Confidential Information").
 * You * shall not disclose such Confidential Information and shall use it only in accordance with the terms of the license agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.alert.web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.alert.bean.MtmUpdateAlertRecipient;
import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertLogAction;
import com.dcivision.alert.bean.UpdateAlertSystemLog;
import com.dcivision.alert.bean.UpdateAlertType;
import com.dcivision.alert.core.AbstractMessageInfo;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.alert.core.DocumentMessageInfo;
import com.dcivision.alert.core.EmailRuleMessageInfo;
import com.dcivision.alert.core.MeetingMessageInfo;
import com.dcivision.alert.core.MessageDetailInfo;
import com.dcivision.alert.core.MessageFormatter;
import com.dcivision.alert.core.MessageFormatterFactory;
import com.dcivision.alert.dao.MtmUpdateAlertRecipientDAObject;
import com.dcivision.alert.dao.UpdateAlertSystemLogDAObject;
import com.dcivision.alert.dao.UpdateAlertTypeDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.web.AbstractAction;

/**
 * <p>
 * Class Name: EditMessageDetailAction.java
 * </p>
 * 
 * @author Greatwall shao
 * @company DCIVision Limited
 * @creation date 2006-09-24
 */
public class EditMessageDetailAction extends AbstractAction {

  private static final String DocumentNotification = "DN";
  
  private static final String DocumentNotificationForEmail = "DNE";

  private static final String DocumentInvitation   = "DI";
  
  private static final String DocumentInvitationForEmail = "DIE";

  private static final String MeetingNotification  = "MN";

  private static final String MeetingInvitation    = "MI";

  private static final String EmailRuleNotification  = "EN";
  
  private static final String ErrorMessage = "EM";

  public String getFunctionCode() {
    return null;
  }

  public String getMajorDAOClassName() {
    return null;
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
      HttpServletResponse response) throws Exception {
    request.setAttribute(GlobalConstant.ACTION_MODE, GlobalConstant.NAV_MODE_VIEW);
    EditMessageDetailForm messageForm = (EditMessageDetailForm)form;
    if(!Utility.isEmpty(request.getParameter("isFromEmail"))){
      Connection dbConn = (Connection) request.getAttribute(GlobalConstant.DB_KEY);
      SessionContainer sessionContainer = this.getSessionContainer(request);
      PermissionManager permissionManager = sessionContainer.getPermissionManager();
      List userGroupIDList = Utility.getPropertyList(permissionManager.getUserGroups(), "ID");
      List userRoleIDList = Utility.getPropertyList(permissionManager.getUserRoles(), "ID");
      boolean isValidUser = false;
      MtmUpdateAlertRecipientDAObject mtmUpdateAlertRecipientDAObject =
        new MtmUpdateAlertRecipientDAObject(sessionContainer,dbConn);
      Integer updateAlertTypeID = TextUtility.parseIntegerObj(messageForm.getUpdateAlertTypeID());
      
        List tempList = mtmUpdateAlertRecipientDAObject.getByUpdateAlertTypeID(updateAlertTypeID);
      for(int i=0;i<tempList.size();i++){
        MtmUpdateAlertRecipient mtmUpdateAlertRecipient = (MtmUpdateAlertRecipient)tempList.get(i);
        Integer recipientID = mtmUpdateAlertRecipient.getRecipientID();
        String recipientType = mtmUpdateAlertRecipient.getRecipientType();
        if(UpdateAlert.USER_RECIPIENT.equalsIgnoreCase(recipientType)
            &&sessionContainer.getUserRecordID().equals(recipientID))
        {
          isValidUser = true;
          break;
        }
        if(UpdateAlert.GROUP_RECIPIENT.equalsIgnoreCase(recipientType)
            &&userGroupIDList.contains(recipientID))
        {
          isValidUser = true;
          break;
        }
        if(UpdateAlert.ROLE_RECIPIENT.equalsIgnoreCase(recipientType)
            &&userRoleIDList.contains(recipientID))
        {
          isValidUser = true;
          break;
        }
      }
      if(!isValidUser){
        //response.sendRedirect(SystemParameterFactory.getSystemParameter(
          //  SystemParameterConstant.APPLICATION_BASE_URL)+"/ListSystemMessage.do");
    	  this.addError(request, "errors.dms.have_no_function_permission","read this message");
    	  return  mapping.findForward(ErrorMessage); 
      }
      request.setAttribute("isFromEmail", "yes");
      UpdateAlertSystemLogDAObject UpdateAlertSystemLogDAObject = 
        new UpdateAlertSystemLogDAObject(sessionContainer,dbConn);
      UpdateAlertSystemLog updateAlertSystemLog = 
        (UpdateAlertSystemLog) UpdateAlertSystemLogDAObject.getInvitationSystemLogByUpdateAlertTypeID(updateAlertTypeID);
      messageForm.setSystemLogID(String.valueOf(updateAlertSystemLog.getID()));
    }
    return forward(mapping, form, request, response);
  }

  private ActionForward forward(ActionMapping mapping, ActionForm form, HttpServletRequest request,
      HttpServletResponse response) throws ApplicationException {
    EditMessageDetailForm messageForm = (EditMessageDetailForm)form;
    String messageType =messageForm.getMessageType().trim();
    String objectID = messageForm.getObjectid() ;
    String systemLogIDstr =messageForm.getSystemLogID();
    String unRead = messageForm.getUnRead()  ;
    String replyType = messageForm.getReplyType()  ;
    String updateAlertID = messageForm.getUpdateAlertID()  ;
    String message = messageForm.getMessage()  ;
    String isList = messageForm.getIsList();
    request.setAttribute("isList", isList);

    Connection dbConn = (Connection) request.getAttribute(GlobalConstant.DB_KEY);
    SessionContainer sessionContainer = this.getSessionContainer(request);


    Integer objectid = TextUtility.parseIntegerObj(objectID);
    UpdateAlertSystemLogDAObject alertSystemLogDAO = new UpdateAlertSystemLogDAObject(
        sessionContainer, dbConn);
    Integer systemLogID = TextUtility.parseIntegerObj(systemLogIDstr);
    UpdateAlertSystemLog alertSystemLog = alertSystemLogDAO.getSystemLogBeanByID(systemLogID);
    if(Utility.isEmpty(alertSystemLog)){
      this.addError(request, "dms.message.document_been_deleted","This");
      return  mapping.findForward(ErrorMessage);    
    }
    MessageFormatter messageFormatter = MessageFormatterFactory.getInstance().getMessageFormatter(alertSystemLog,sessionContainer,dbConn);
    AbstractMessageInfo messageInfo =null;
    ActionForward forward = null;

    this.setSystemLogToRead(request, systemLogID, unRead);
    if (messageType.equalsIgnoreCase("meetingInvitation")) {
      messageInfo = getMeetingMessgeIfo(request, dbConn, sessionContainer, objectid,alertSystemLog,
                                                        messageFormatter,systemLogIDstr);
      if(!Utility.isEmpty(replyType))
      {

        replyOnInvite(request, replyType, updateAlertID, message, dbConn, sessionContainer, systemLogID);
        try {
          response.setContentType("text/plain");
          response.getWriter().write(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "message.invite.reply.information"));
        }
        catch (IOException e) {
          log.error(e, e);
        }        
        return null;
      }
      forward = mapping.findForward(MeetingInvitation);
    }
    else
    {
      if (!Utility.isEmpty(unRead)) {
        return null;
      }
    }

    if (messageType.equalsIgnoreCase("meetingNotification")) {
      messageInfo = getMeetingMessgeIfo(request, dbConn, sessionContainer, objectid,alertSystemLog,
                                                              messageFormatter,systemLogIDstr);
     
      forward = mapping.findForward(MeetingNotification);
    }
    
    if (messageType.equalsIgnoreCase("documentInvitation")) {
      messageInfo = getDocumentMessgeIfo(request, dbConn, sessionContainer, objectid,alertSystemLog,
                                                          messageFormatter,systemLogIDstr);
      if(!Utility.isEmpty(request.getParameter("isFromEmail"))){
        request.setAttribute("HEADER_FOLDER_NAME", MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.message.system.message"));
        forward = mapping.findForward(DocumentInvitationForEmail);
      } else {
        forward = mapping.findForward(DocumentInvitation);
      }
    }
    
    if (messageType.equalsIgnoreCase("documentNotification")) {
      messageInfo = getDocumentMessgeIfo(request, dbConn, sessionContainer, objectid,alertSystemLog,
                                                        messageFormatter,systemLogIDstr);
      if(!Utility.isEmpty(request.getParameter("isFromEmail"))){
        request.setAttribute("HEADER_FOLDER_NAME", MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "home.message.system.message"));
        forward = mapping.findForward(DocumentNotificationForEmail);
      } else {
        forward = mapping.findForward(DocumentNotification);
      }
    }
    if (messageType.equalsIgnoreCase("emailRuleNotification")) {
      messageInfo = getEmailRuleMessgeIfo(request, dbConn, sessionContainer, objectid,alertSystemLog,
                                                        messageFormatter,systemLogIDstr);
      
      forward = mapping.findForward(EmailRuleNotification);
    }
    if(messageInfo!=null)
    {
    setMessageInfo2Request(request, messageInfo);
    }
    try{
      dbConn.commit();      
    }
    catch (SQLException e) {
      log.error(e, e);
    }finally{}
    return forward;
  }

  private void replyOnInvite(HttpServletRequest request, String replyType, String updateAlertID, String message, Connection dbConn, SessionContainer sessionContainer, Integer systemLogID) throws ApplicationException {
    if (UpdateAlert.ACCEPT_ON_REPLY.equals(replyType)) 
    {
    replyOnInvite(request, replyType, systemLogID);
    }
    AlertManager alertManager = new AlertManager(sessionContainer, dbConn);
    alertManager.createUpdateAlertSystemLog(TextUtility.parseIntegerObj(updateAlertID), null,
        replyType, message);

    try {
     this.commit(request);
    }
    catch (Exception e) {
      log.error(e, e);
    }
  }
  
  private AbstractMessageInfo getDocumentMessgeIfo(HttpServletRequest request, Connection dbConn, 
                      SessionContainer sessionContainer, Integer objectid, UpdateAlertSystemLog alertSystemLog, 
                      MessageFormatter messageFormatter, String systemLogID) {
  DocumentMessageInfo documentMessage = new DocumentMessageInfo(objectid);
  documentMessage.setSessionContainer(sessionContainer);
  documentMessage.setConnection(dbConn);
  documentMessage.setAlertSystemLog(alertSystemLog);
  documentMessage.setMessageFormatter(messageFormatter);
    return documentMessage;
  }
  private AbstractMessageInfo getMeetingMessgeIfo(HttpServletRequest request, Connection dbConn, 
      SessionContainer sessionContainer, Integer objectid, UpdateAlertSystemLog alertSystemLog,
      MessageFormatter messageFormatter, String systemLogID) throws ApplicationException {
    AbstractMessageInfo meetingMessage = new MeetingMessageInfo(objectid);
    meetingMessage.setSessionContainer(sessionContainer);
    meetingMessage.setConnection(dbConn);
    meetingMessage.setAlertSystemLog(alertSystemLog);
    meetingMessage.setMessageFormatter(messageFormatter);
    return meetingMessage;
  } 
  private AbstractMessageInfo getEmailRuleMessgeIfo(HttpServletRequest request, Connection dbConn, 
      SessionContainer sessionContainer, Integer objectid, UpdateAlertSystemLog alertSystemLog,
      MessageFormatter messageFormatter, String systemLogID) throws ApplicationException {
    AbstractMessageInfo emailRuleMessage = new EmailRuleMessageInfo();
    emailRuleMessage.setSessionContainer(sessionContainer);
    emailRuleMessage.setConnection(dbConn);
    emailRuleMessage.setAlertSystemLog(alertSystemLog);
    emailRuleMessage.setMessageFormatter(messageFormatter);
    return emailRuleMessage;
  } 

  public void replyOnInvite(HttpServletRequest request, String replyType, Integer systemLogID)
      throws ApplicationException {
    Connection connection = this.getConnection(request);

    
    try {
      SessionContainer sessionContainer = this.getSessionContainer(request);
      
        try {
          String recipientType = GlobalConstant.OBJECT_TYPE_UDF;
          UpdateAlertSystemLogDAObject updateAlertSystemLogDAO = new UpdateAlertSystemLogDAObject(
              sessionContainer, connection);
          UpdateAlertSystemLog tmpUpdateAlertSystemLog = (UpdateAlertSystemLog) updateAlertSystemLogDAO
              .getObjectByID(systemLogID);
          UpdateAlertTypeDAObject updateAlertTypeDAO = new UpdateAlertTypeDAObject(
              sessionContainer, connection);
          UpdateAlertType tmpUpdateAlertType = (UpdateAlertType) updateAlertTypeDAO
              .getObjectByID(tmpUpdateAlertSystemLog.getUpdateAlertTypeID());
          Integer recipientID = sessionContainer.getUserRecordID();
          Integer update_alert_id = tmpUpdateAlertType.getUpdateAlertID();
          tmpUpdateAlertType = (UpdateAlertType) updateAlertTypeDAO
              .getIDByUpdateAlertIDAndActionType(update_alert_id, UpdateAlert.REMIND_ACTION);
          if (tmpUpdateAlertType != null) {
            Integer update_alert_type_id_r = tmpUpdateAlertType.getID();
            MtmUpdateAlertRecipientDAObject mtmAlertRecipientDAO = new MtmUpdateAlertRecipientDAObject(
                sessionContainer, connection);
            MtmUpdateAlertRecipient recipient = (MtmUpdateAlertRecipient) mtmAlertRecipientDAO
                .getByRecipientIDs(recipientID, recipientType, update_alert_id,
                    update_alert_type_id_r);
            mtmAlertRecipientDAO.updateByID(recipient.getID());
          }
        } catch (Exception e) {
          log.error(e, e);
        }
     

      connection.commit();

    }catch (Exception e) {
      log.error("Retrieve calendar record information.", e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }
  }
  private void setSystemLogToRead(HttpServletRequest request,
      Integer systemLogID, String unRead)
      throws ApplicationException {
    Connection conn = this.getConnection(request);
    AlertManager alertManager = new AlertManager(this.getSessionContainer(request), conn);
    if (systemLogID != null) {
      if (alertManager.checkForSystemLogActionByActionType(systemLogID,
          UpdateAlertLogAction.READ_ACTION)) {
        if (!Utility.isEmpty(unRead)) {
          alertManager.deleteLogActionBySystemLogIDCurActor(systemLogID);
        }
      } else {
        UpdateAlertSystemLog systemLog = new UpdateAlertSystemLog();
        systemLog.setID(systemLogID);
        alertManager.createSystemLogAction(systemLog, UpdateAlertLogAction.READ_ACTION, null, null);
      }
    }
    try {
      conn.commit();
    }
    catch (SQLException e) {
      log.error(e, e);
    }

  }

  private void setMessageInfo2Request(HttpServletRequest request, MessageDetailInfo messageInfo)
      throws ApplicationException {
	  /*
	   * joan.xiong update code for bug EIP-681 by 2006/11/03
	   */
	  try{
		    AbstractBaseObject messageBean = messageInfo.getMessageInfo();
		    request.setAttribute("messageBean", messageBean);
	  }catch(Exception e){
		  this.addError(request,"errors.dms.meeting_event_is_deleted");
	  }
	  /*
	   * joan.xiong update code end
	   */
  }


}